<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-04-03
 * @Time: 16:35
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Goods.php
 */
namespace app\common\model\zds;

use app\admin\model\SysAdmin;
use app\api\model\curriculum\Curriculum;
use app\common\model\curriculum\CurriculumVideo;
use think\Db;
use think\Model;
use think\Request;

/**
 * Class Goods
 * @package app\common\model\zds
 *
 * @property mixed id
 * @property mixed customerid
 * @property mixed userid
 * @property mixed goods_type
 * @property mixed goodsid
 */
class Goods extends Model {
    protected $table = 'zds_goods';
    protected $pk = 'id';

    /***
     * getUserCourse
     * 获取指定用户（销售系统客户）的可购买课程
     *
     * @author zhengkai
     * @date 2018-04-03
     *
     * @param int $userId 掌乾用户id
     * @param int $page 当前页数
     * @param int $limit 每页条数
     */
    public static function getUserCourse($userId, $page=0, $limit=10)
    {
        $data = self::alias('g')
            ->join('curriculum c', 'g.goodsid=c.curriculum_id', 'left')
            ->join('curriculum_class cc', 'c.curriculum_class=cc.class_id', 'left')
            ->field('
            c.curriculum_id,
            c.curriculum_name,
            c.curriculum_pic,
            c.curriculum_summary,
            c.curriculum_sale_price as curriculum_price,
            c.curriculum_level,
            c.buy_total,
            c.view_total,
            cc.class_name
            ')
            ->where('g.goods_type', 1)
            ->where('g.userid', $userId)
            ->where('c.hide=false' )
            ->order('g.id desc')
            ->limit($page, $limit)
            ->select();
        return $data;
    }

    /**
     * queryVipCurriculum
     * 根据条件查询vip课程数据
     *
     * @author zhengkai
     * @date 2018-04-10
     * @version 1.4.1
     *
     * @param int $uid 用户id
     * @param int $rows 每页显示数据条数
     * @param int $page 当前第x页
     * @return \think\response\Json
     */
    public static function queryVipCurriculum($uid, $rows=10, $page=1)
    {
        $filter_param = Request::instance()->param();

        $params = ['limit' => $rows, 'offset' => intval(($page - 1) * $rows)];

        $condition=[
            'g.goods_type'=>1,
            'g.userid'=>$uid,
            'c.hide'=>'false'
        ];
        if(!empty($filter_param['key'])){
            $condition['c.curriculum_name|c.curriculum_summary']=['like','%'.$filter_param['key'].'%','_multi'=>true];
        }
        if(!empty($filter_param['class'])){
            $condition['curriculum_class']=$filter_param['class'];
        }
        if(!empty($filter_param['teacher'])){
            $curriculumId= CurriculumVideo::where('video_teacher',$filter_param['teacher'])->distinct('video_curriculum')->column('video_curriculum');
            $condition['curriculum_id'] = empty($curriculumId) ? 0 : ['in',$curriculumId];
        }
        switch ($filter_param['sort'] ?? null) {
            // 默认排序
            case 'asc':
                $order = 'c.curriculum_addtime asc';
                break;

            // 价格排序
            case 'price_asc':
                $order =  'c.curriculum_sale_price asc';
                break;
            case 'price_desc':
                $order =  'c.curriculum_sale_price desc';
                break;

            // 评价分数排序
            case 'score_asc':
                $order =  'c.comment_score asc';
                break;
            case 'score_desc':
                $order =  'c.comment_score desc';
                break;

            // 销量排序
            case 'sales_asc':
                $order = 'c.buy_total asc';
                break;
            case 'sales_desc':
                $order = 'c.buy_total desc';
                break;

            // 视频观看数排序
            case 'view_asc':
                $order = 'c.view_total asc';
                break;
            case 'view_desc':
                $order = 'c.view_total desc';
                break;

            // 课程难度等级排序
            case 'level_asc':
                $order =  'c.curriculum_level asc';
                break;
            case 'level_desc':
                $order =  'c.curriculum_level desc';
                break;
            default :
                $order = 'c.curriculum_id desc';
        }

        $data = self::alias('g')
            ->join('curriculum c', 'g.goodsid=c.curriculum_id', 'left')
            ->join('curriculum_class cc', 'c.curriculum_class=cc.class_id', 'left')
            ->join('sales ss','c.curriculum_sales=ss.sales_id','left')
            ->field('
              c.curriculum_id,
              c.curriculum_name,
              c.curriculum_pic,
              c.curriculum_summary,
              c.curriculum_description,
              c.curriculum_sale_price,
              c.curriculum_market_price,
              c.curriculum_sales,
              c.curriculum_suit_user,
              c.curriculum_type,
              c.curriculum_level,
              cc.class_name as curriculum_class,
              c.sales_volume,
              c.buy_total,
              c.view_total,
              c.video_view,
              c.curriculum_episode_number video_total,
              ss.sales_type,
              ss.sales_discount,
              ss.sales_amount,
              ss.sales_start_time,
              ss.sales_end_time,
              c.apple_pay_price,
              c.apple_pay_production_id
            ')
            ->where($condition)
            ->order($order)
            ->page($page, $rows)
            ->select();
        $now = time();
        foreach ($data as & $val) {
            // 课程销量处理
            $buy_total = $val['sales_volume']<$val['buy_total']?$val['buy_total']:$val['sales_volume'];
            $val['buy_total'] = num2tring($buy_total);
            // 视频观看总数处理
            $view_total = $val['view_total']<$val['video_view']?$val['video_view']:$val['view_total'];
            $val['view_total'] = num2tring($view_total);

            $val['curriculum_summary'] = str_replace('&nbsp;', '', stripHtml($val['curriculum_summary']));
            $val['curriculum_description'] = str_replace('&nbsp;', '', stripHtml($val['curriculum_description']));

            switch ($val['curriculum_level']) {
                case 1:
                    $val['curriculum_level'] = '初级';
                    break;
                case 2:
                    $val['curriculum_level'] = '中级';
                    break;
                case 3:
                    $val['curriculum_level'] = '高级';
                    break;
            }

            $sales_val = 0; // 活动优惠
            if ($val['curriculum_sales']>0 && ($val['sales_start_time']<=$now && $now<=$val['sales_end_time'])) {
                switch ($val['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(((int)$val['sales_discount']/10), 1).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$val['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$val['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$val['sales_amount']);
                        break;
                }
            }
            $val['curriculum_sales'] = $val['curriculum_sales']?$sales_val:0;

            $teacher = Curriculum::getTeacher($val['curriculum_id'], 't.realname');
            $val['curriculum_teacher'] = $teacher?$teacher[0]['realname']:"";

            $val['is_buy'] = self::isBuy($uid, $val['curriculum_id']);

            unset($val['sales_type'],$val['sales_discount'],$val['sales_amount'],$val['sales_start_time'],$val['sales_end_time']);
        }

        unset($params['limit'],$params['offset']);

        $total=self::alias('g')->join('curriculum c', 'g.goodsid=c.curriculum_id', 'left')->join('curriculum_class cc', 'c.curriculum_class=cc.class_id', 'left')->where($condition)->count();

        $pageTotal = intval(ceil($total / $rows));

        // 重组输出数组
        $result = [
//            'page_total' => ceil(count($arr1)/$rows), // 总页数
            'page_total' => $pageTotal, // 总页数
            'list' => $data
        ];
        return $result;
    }

    private static function isBuy($uid, $curriculum_id)
    {
        if (SysAdmin::checkAdminUser($uid)) return 1;
        /*$result  = Db::table('user_buy_curriculum')
            ->where('uc_user', $uid)
            ->where('uc_curriculum', $curriculum_id)
            ->count('uc_id');*/

        $sql = <<<SQL
select count(uc_id) as uc_num from user_buy_curriculum where uc_user={$uid} and uc_curriculum={$curriculum_id};
SQL;
        $result = Db::query($sql);
        $result = $result[0]['uc_num'];

        if ($result) {
            return 1; // 已购买
        } else {
            return 0; // 未购买
        }
    }
}